var fs = require('fs');
var lame = require('lame');
var path = require('path');
require('bufferjs');
/**
 * Hier bauen wir rein:
 * -audio chunk "stream" mit startPos
 * -user file import/(admin file import)  ->dumbdb.js code verwenden
 * 
 * 
 */
module.exports = function(){
	
	
//user upload aufbereiten und speichern??
	var saveStream = function(url, depth){
		
	};
	
	/**
	 * @param file string relative 2 mp3
	 * @param fn function(err, buffer)
	 */
	var getChunkStream = function(file, start, fn, end){
		var bundleCount = 0;
		var buffer = null;
		var parser = lame.createParser();
		var test = {};
		var count = 0;
		var count2 = 0;
		var count3 = 0;
		parser.on('header', function(b){
//			test[b.toString('base64')] = b.toString('base64');
//			if(count2++<6) console.log('header:\r\n');//, b.toString('hex') );
			if(buffer == null){
				buffer = new Buffer(b);//.toString('base64');
			}else{
				buffer = Buffer.concat(buffer, b);
			}
		})
		parser.on('frame', function(b){
//				if(count3++<6)console.log('frame:\r\n');//, b.toString('base64') );
			if(bundleCount >= 50){
				buffer = Buffer.concat(buffer, b);
				fn(null, buffer);
//				von den buffern kann chrome nur den ersten(letzten) lesen
//				if(count++<5)console.log('buffer:\r\n');//,buffer.toString('base64'));
				
				buffer = null;
				bundleCount = 0;
			}else{
				buffer = Buffer.concat(buffer, b);
				bundleCount++;
			}
//			if(buffer != null){
//				buffer = Buffer.concat(buffer, b);
//			}
//			bundleCount++;
		});
		parser.on('end', function(b){
			//console.log(test);
			if(buffer!=null){
				if(b!=null) Buffer.concat(buffer, b);
				fn(null,buffer);
				console.log('Done sending file %s', file)
				end();
			}
		});

		fs.createReadStream(path.join('/home/bolu/colamix/mp3', file), {start: 0}).pipe(parser);
	};
	
	
	
	
	
	return {
		getChunkStream: getChunkStream,
	};
};